﻿using GalaSoft.MvvmLight.Command;
using KJSync.Access.Models;
using KJSyncXP.Sqlite.Model;
using KJSyncXP.SQLite.Context;
using KJSyncXP.Views.pop;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Windows;
using System.Windows.Input;

namespace KJSyncXP.ViewModels
{
    public class ShiftItemViewModel : BaseViewModel
    {
        public RelayCommand UpdateShiftCountCommand { get; private set; }

        public RelayCommand SaveShiftCommand { get; private set; }

        private readonly SqliteDbContext _sqliteCtx;

        private int _totalShiftCount;
        public int TotalShiftCount
        {
            get => _totalShiftCount;
            set
            {
                if (value < 1) value = 1; // 防止输入非正整数
                _totalShiftCount = value;
                RaisePropertyChanged("TotalShiftCount");
            }
        }

        private ObservableCollection<ShiftItem> _shiftItems = new ObservableCollection<ShiftItem>();
        public ObservableCollection<ShiftItem> ShiftItems
        {
            get => _shiftItems;
            set
            {
                _shiftItems = value;
                RaisePropertyChanged("ShiftItems"); // 通知UI属性变更
            }
        }

        public ShiftItemViewModel(SqliteDbContext sqliteCtx)
        {
            _sqliteCtx = sqliteCtx;
            UpdateShiftCountCommand = new RelayCommand(UpdateShiftItems); // 绑定更新命令
            SaveShiftCommand = new RelayCommand(SaveShiftItems); // 绑定保存命令
            LoadShiftItems(); // 初始化加载班次
        }


        // 加载班次（优先从数据库读取，无数据则初始化并入库）
        private void LoadShiftItems()
        {
            var dbShiftItems = _sqliteCtx.Db.Queryable<ShiftItem>().ToList();
            if (dbShiftItems.Any())
            {
                ShiftItems = new ObservableCollection<ShiftItem>(dbShiftItems);
                TotalShiftCount = dbShiftItems.Count; // 同步总班次数
            }
            else
            {
                // 数据库无数据，初始化2个默认班次并入库
                var defaultShifts = new List<ShiftItem>
                {
                    new ShiftItem { ShiftName = "早班", StartTime = "08:00", EndTime = "20:00" },
                    new ShiftItem { ShiftName = "晚班", StartTime = "20:00", EndTime = "08:00" }
                };
                _sqliteCtx.Db.Insert(defaultShifts).ExecuteAffrows();
                ShiftItems = new ObservableCollection<ShiftItem>(defaultShifts);
                TotalShiftCount = defaultShifts.Count;
            }
        }

        // 根据总班次数更新班次列表（清空后新生成/同步数据库）
        private void UpdateShiftItems()
        {
            try
            {
                // 清空现有内存数据
                ShiftItems.Clear();

                //生成新的班次（若数据库有对应数量，优先读库；否则新建）

                var newShifts = new List<ShiftItem>();
                for (int i = 0; i < TotalShiftCount; i++)
                {
                    var shiftItem = new ShiftItem();
                    newShifts.Add(shiftItem);
                }

                ShiftItems = new ObservableCollection<ShiftItem>(newShifts);
              
            }
            catch (Exception ex)
            {
                // 异常处理（可根据需求添加日志）
                System.Diagnostics.Debug.WriteLine($"更新班次失败：{ex.Message}");
            }
        }


        private void SaveShiftItems() {

            // 1. 数据校验（避免空数据保存）
            if (ShiftItems == null || !ShiftItems.Any())
            {
                MessageBox.Show("无班次数据可保存，请先配置班次信息！", "提示",
                                MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                var saveShifts = ShiftItems.ToList();

                _sqliteCtx.Db.Delete<ShiftItem>().Where(a => true).ExecuteAffrows();

                var insertCount = _sqliteCtx.Db.Insert(saveShifts).ExecuteAffrows();

                if (insertCount == saveShifts.Count)
                {
                    MessageBox.Show($"班次数据保存成功！共保存 {insertCount} 条班次信息", "成功",
                                    MessageBoxButton.OK, MessageBoxImage.Information);

                    var currentWindow = Application.Current.Windows.OfType<ShiftItemWindow>().FirstOrDefault();
                    currentWindow?.Close();
                }
                else
                {
                    MessageBox.Show($"班次数据保存异常！待保存 {saveShifts.Count} 条，实际插入 {insertCount} 条",
                                    "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"班次数据保存失败：{ex.Message}", "错误",
                                MessageBoxButton.OK, MessageBoxImage.Error);

            }
        } 
    }
}